package com.qut.graduate.busrtquery.ui.user;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.qut.graduate.busrtquery.BRTQCache;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.BaseActivity;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.presenter.PictureSelector;
import com.qut.graduate.busrtquery.presenter.UserCenterPresenter;
import com.qut.graduate.busrtquery.utils.net.BmobCollectUtils;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.net.NetworkUtils;
import com.qut.graduate.busrtquery.utils.uiabout.StatusBarUtils;
import com.qut.graduate.busrtquery.view.WavePageView;

import java.io.File;

import cn.bmob.v3.BmobUser;

/**
 * 用户中心界面
 * 可以管理查询历史记录，查看收藏的地点、线路等
 *
 * @Author WLL
 * @Time: 2019/3/28 9:57
 */
public class UserCenterActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "UserCenterActivity";
    private UserCenterActivity mContext;
    private UserCenterPresenter presenter;
//    private SPUtils mSPUtils;
    private User user;
    private String savePath;
    private Toolbar toolbar;
    private TextView toolbarTitle;
    private FrameLayout mUserHeaderLayout;
    private ImageView mUserHeaderBg;
    private WavePageView mUserWaveView;
    private LinearLayout mUserAnimLayout;
    private RoundedImageView mUserAnimImage;
    private EditText mUserAnimText;
    private TextView mUserLineCollect;
    private TextView mUserStationCollect;
    private TextView mUserResetPassword;
    private LinearLayout mUserExitLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_usercenter;
    }

    @Override
    protected void init() {
//        mSPUtils = SPUtils.getInstance(getApplicationContext());
        presenter = new UserCenterPresenter(this);
        mContext = UserCenterActivity.this;
        initView();
        initEvent();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateNowTheme();
        initUserInfo();
    }

    private void updateNowTheme() {
        toolbar.setPopupTheme(getPopupToolbarStyle());
        //layout_toolbar.setBackgroundColor(getPrimaryColor());
        toolbar.setTitle("");
        mUserHeaderLayout.setBackgroundColor(getPrimaryColor());
        StatusBarUtils.drawableStatusBar(this, Color.TRANSPARENT, false);
        updateBarColor();
    }

    /**
     * 加载用户的昵称、图片、背景图片
     */
    public void initUserInfo() {
        if (user != null) {
            mUserAnimText.setText(user.getUsername());
        } else {
            mUserAnimText.setText("未知错误，无法获取到昵称");
        }
        loadUserImage();
    }

    public void loadUserImage() {
        String headerPath = preferenceUtils.getString(getString(R.string.preference_user_header_path), "");
        String bgPath = preferenceUtils.getString(getString(R.string.preference_user_bg_path), "");
        File headerFile = new File(headerPath);
        File bgFile = new File(bgPath);
        // 当前网络状态
        if (!(NetworkUtils.getNetworkType(this) == BRTQConstant.NETWORK_NONE)) {
            if (!headerPath.equals("") && headerFile.exists()) {
                Glide.with(this).load(headerPath).into(mUserAnimImage);
            } else if (user.getHeadImg() != null && user.getHeadImg().getFileUrl() != null) {
                presenter.downloadFile(BRTQConstant.BMOB_IMAGE_HEADER);
            } else {
                Glide.with(this).load(R.mipmap.detach_male).into(mUserAnimImage);
            }
            if (!bgPath.equals("") && bgFile.exists()) {
                Glide.with(this).load(bgPath).into(mUserHeaderBg);
            } else if (user.getBgImg() != null && user.getBgImg().getFileUrl() != null) {
                presenter.downloadFile(BRTQConstant.BMOB_IMAGE_BG);
            } else {
                mUserHeaderLayout.setBackgroundColor(getPrimaryColor());
            }
        } else {
            // 没有网络从本地加载
            if (!headerPath.equals("") && headerFile.exists()) {
                Glide.with(this).load(headerPath).into(mUserAnimImage);
            } else {
                Glide.with(this).load(R.mipmap.detach_male).into(mUserAnimImage);
            }
            if (!bgPath.equals("") && bgFile.exists()) {
                Glide.with(this).load(bgPath).into(mUserHeaderBg);
            } else {
                mUserHeaderLayout.setBackgroundColor(getPrimaryColor());
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_header_anim_image:
                selectPicture(mUserAnimImage);
                break;
            case R.id.user_header_layout:
                selectPicture(mUserHeaderBg);
                break;
            case R.id.user_center_line_collect:
                Intent intent = new Intent(UserCenterActivity.this, CollectActivity.class);
                intent.putExtra("collectType", BRTQConstant.COLLECT_BUS_LINE);
                startActivity(intent);
                break;
            case R.id.user_center_station_collect:
                Intent intent1 = new Intent(UserCenterActivity.this, CollectActivity.class);
                intent1.putExtra("collectType", BRTQConstant.COLLECT_STATION);
                startActivity(intent1);
                break;
            case R.id.user_center_reset_password:
                Intent intent2 = new Intent(UserCenterActivity.this, LoginActivity.class);
                intent2.putExtra("resetPassword","resetPassword");
                startActivity(intent2);
                break;
            case R.id.user_exit_login_layout:
                exitLogin();
                break;
        }
    }

    /**
     * 退出登录功能
     */
    public void exitLogin() {
        User user = BmobUser.getCurrentUser(User.class);
        BmobCollectUtils.updateBmobBusLines(user);
        BmobCollectUtils.updateBmobStationInfos(user);
        deleteCurUserImage();
        User.logOut();
        preferenceUtils.setIsFirstLoginToUserCenter(true);
        finish();
        overridePendingTransition(R.anim.activity_screen_zoom_in, R.anim.activity_screen_zoom_out);
    }

    /**
     * 删除当前用户的本地相关图片
     */
    public void deleteCurUserImage(){
        String headerPath = preferenceUtils.getString(getString(R.string.preference_user_header_path), "");
        String bgPath = preferenceUtils.getString(getString(R.string.preference_user_bg_path), "");
        File headerFile = new File(headerPath);
        File bgFile = new File(bgPath);
        if (headerFile.exists()) headerFile.delete();
        if (bgFile.exists()) bgFile.delete();
        preferenceUtils.putString(getString(R.string.preference_user_header), "");
        preferenceUtils.putString(getString(R.string.preference_user_header_path), "");
    }

    /**
     * 选择图片按钮点击事件
     * create() 方法参数一是上下文，在activity中传activity.this，在fragment中传fragment.this
     * 参数二为请求码，用于结果回调onActivityResult中判断
     * selectPicture()方法参数分别为:是否裁剪、裁剪后图片的宽(单位px)、裁剪后图片的高、宽比例、高比例
     * 默认为裁剪，宽200，高200，宽高比例为1：1
     *
     * @param view
     */
    public void selectPicture(View view) {
        if (view.getId() == R.id.user_header_anim_image)
            PictureSelector.create(UserCenterActivity.this, BRTQConstant.SELECT_HEADER_REQUEST_CODE)
                    .selectPicture(true, 400, 400, 1, 1);
        if (view.getId() == R.id.user_header_bg)
            PictureSelector.create(UserCenterActivity.this, BRTQConstant.SELECT_HEADER_BG_REQUEST_CODE)
                    .selectPicture(true, 800, 400, 2, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 用户头像结果回调
        if (requestCode == BRTQConstant.SELECT_HEADER_REQUEST_CODE) {
            loadUserImage(data, mUserAnimImage);
        }
        // 用户背景结果回调
        if (requestCode == BRTQConstant.SELECT_HEADER_BG_REQUEST_CODE) {
            loadUserImage(data, mUserHeaderBg);
        }
    }

    /**
     * 用户选择完图片后调用，用来加载图片，保存图片信息，上传该信息到bomb服务器
     *
     * @param intent
     * @param view
     */
    public void loadUserImage(Intent intent, View view) {
        if (intent != null) {
            final String picturePath = intent.getStringExtra(BRTQConstant.PICTURE_PATH);
            String pictureName = picturePath.substring(picturePath.lastIndexOf("/") + 1);
            Glide.with(this).load(picturePath).into((ImageView) view);
            LogUtils.d("----用户中心界面 选择完图片后，图片地址" + picturePath, this.getClass());
            LogUtils.d("----用户中心界面 选择完图片后，图片名称" + pictureName, this.getClass());
            if (view.equals(mUserAnimImage)) {
                preferenceUtils.putString(getString(R.string.preference_user_header), pictureName);
                preferenceUtils.putString(getString(R.string.preference_user_header_path), picturePath);
                presenter.uploadPic(picturePath, BRTQConstant.BMOB_IMAGE_HEADER);
            }
            if (view.equals(mUserHeaderBg)) {
                toolbar.setBackgroundColor(Color.TRANSPARENT);
                preferenceUtils.putString(getString(R.string.preference_user_bg), pictureName);
                preferenceUtils.putString(getString(R.string.preference_user_bg_path), picturePath);
                presenter.uploadPic(picturePath, BRTQConstant.BMOB_IMAGE_BG);
            }
        }
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbarTitle = findViewById(R.id.toolbar_title);
        setSupportActionBar(toolbar);
        mUserHeaderLayout = findViewById(R.id.user_header_layout);
        mUserHeaderBg = findViewById(R.id.user_header_bg);
        mUserWaveView = findViewById(R.id.user_header_wave_view);
        mUserAnimLayout = findViewById(R.id.user_header_anim_layout);
        mUserAnimImage = findViewById(R.id.user_header_anim_image);
        mUserAnimText = findViewById(R.id.user_header_anim_text);
        mUserLineCollect = findViewById(R.id.user_center_line_collect);
        mUserStationCollect = findViewById(R.id.user_center_station_collect);
        mUserResetPassword = findViewById(R.id.user_center_reset_password);
        mUserExitLayout = findViewById(R.id.user_exit_login_layout);

        mUserLineCollect.setOnClickListener(this);
        mUserStationCollect.setOnClickListener(this);
        mUserResetPassword.setOnClickListener(this);
        mUserExitLayout.setOnClickListener(this);
        mUserAnimImage.setOnClickListener(this);
        mUserHeaderLayout.setOnClickListener(this);
    }

    private void initEvent() {
        final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(300, 300);
        lp.gravity = Gravity.BOTTOM | Gravity.CENTER;
        mUserWaveView.setOnWaveAnimationListener(new WavePageView.OnWaveAnimationListener() {
            @Override
            public void OnWaveAnimation(float y) {
                lp.setMargins(0, 0, 0, (int) y + 150);
                mUserAnimLayout.setLayoutParams(lp);
            }
        });

        toolbarTitle.setText(R.string.user_center);
        toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(R.anim.activity_screen_zoom_in, R.anim.activity_screen_zoom_out);
            }
        });

        LogUtils.d("bmob 登录后未更新前本地数据 getBusLineCollectList:" + BRTQCache.getInstance().getBusLineCollectList()
                +"  getStationInfoCollectList:" + BRTQCache.getInstance().getStationInfoCollectList());
        user = BmobUser.getCurrentUser(User.class);
        if (preferenceUtils.getIsFirstLoginToUserCenter() && user!=null) {
            BmobCollectUtils.updateLocalBusLinesFromBmob(user);
            BmobCollectUtils.updateLocalStationInfosFromBmob(user);
            preferenceUtils.setIsFirstLoginToUserCenter(false);
        }
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public ImageView getmUserHeaderBg() {
        return mUserHeaderBg;
    }

    public RoundedImageView getmUserAnimImage() {
        return mUserAnimImage;
    }

}
